<?php
namespace app\api\controller\order;

use app\common\controller\Api;
use think\Db;
use app\common\controller\Commission;
use Aesutils;
use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup;

class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 订单列表
     * @path api/order/order/index
     */
    public function index()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $where = ['user_id'=>$userId,'store_id'=>$storeId];
        $page = $this->request->param('page',1);
        $orderStatus = $this->request->param('order_status',-1);
        if ($orderStatus != -1) {

            $where['order_status'] = $orderStatus;
        }
        $order = db('order')
            ->where($where)
            ->where('order_type','in',[1,2])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        if (!empty($order)) {
            $order = $order->toArray();
            //$manJian = getOrderManJian($storeId,$totalAmount);
            $goods_count_price = 0;
            $goods_count_num = 0;
            foreach ($order['data'] AS $key => $value) {
                $orderGoods = db('order_goods')->where('order_id',$value['id'])->select();
                $orderGoods = addWebSiteUrl($orderGoods,['goods_pic']);
                foreach ($orderGoods AS $k => $v) {

                    $goods_count_price += $v['price']*$v['num'];
                    $goods_count_num += $v['num'];
                }
                $order['data'][$key]['order_goods'] = $orderGoods;
                $order['data'][$key]['total_price'] = $value['price'];
                $order['data'][$key]['total_num'] = $goods_count_num;
            }

        }
        $this->success('请求成功',$order);
    }

    /**
     * 购物车创建订单
     * @path api/order/order/createOrder
     */
    public function createOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
            $type = $this->request->post('type');//1快递邮寄  2到店自提
            $addressId = $this->request->post('address_id',0);
            $storeId = $this->request->post('store_id',$storeId);//空间/中心/自提点ID
            $cartId = $this->request->post('cart_id');
            $remark = $this->request->post('remark');
            $name = $this->request->post('name');
            $tel = $this->request->post('tel');
            $activeId = $this->request->post('active_id');
            $totalAmount = 0;
            $fx_price = 0;//一级分销总金额
            $fx_price_two = 0;//二级分销总金额
            $fxGoodsIdPriceArr = [];//单个商品一级分销金额  例：goodsId=>1.1
            $fxGoodsIdPriceArrTwo = [];//单个商品二级分销金额  例：goodsId=>1.1
            /***过滤参数***/
            //var_dump($type,$cartId);die;
            if (empty($type) || empty($cartId)) {
                Db::rollback();
                $this->error('缺少参数');
            }

            $isManJian = true;//默认开启满减
            $highuserManjian = db('config')->where(['name'=>'highuser_manjian','group'=>'basic'])->value('value');
            $partnerManjian = db('config')->where(['name'=>'partner_manjian','group'=>'basic'])->value('value');
            $user = db('user')->where('id',$userId)->find();
            if ($user['type'] == 2 && $highuserManjian == 0) {
                //高级用户
                $isManJian = false;
            }
            if ($user['type'] == 3 && $partnerManjian == 0) {
                //合伙人
                $isManJian = false;
            }
            if ($isManJian == false && !empty($activeId)) {
                Db::rollback();
                $this->error('高级用户和合伙人，暂时不支持使用满减活动下单');
            }

            $store = db('store')->where('id',$storeId)->find();
            $address = db('address')->where('id',$addressId)->find();
            $cart = db('cart')
                ->alias('a')
                ->join('goods b','a.goods_id = b.id','left')
                ->where([
                    'a.user_id'=>$userId,
                    'a.store_id'=>$storeId
                ])->
                where('a.id','in',$cartId)
                ->select();
            if (empty($cart)) {
                Db::rollback();
                $this->error('购物车商品不存在');
            }

            foreach ($cart AS $key => $value) {
                $goods = db('store_goods')->where(['store_id'=>$storeId,'goods_id'=>$value['goods_id']])->find();
                $storeGoodsId = $goods['id'];
                $goods = db('store_goods')->where('id',$storeGoodsId)->lock(true)->find();
                $goodsP = db('goods')->where('id',$value['goods_id'])->find();
                $iSonSale = $goodsP['is_on_sale'];
                if ($iSonSale < 1) {
                    Db::rollback();
                    $this->error("'".$value['goods_name']."'产品已下架");
                }
                if ($goods['stock'] < $value['num']) {
                    Db::rollback();
                    $this->error("'".$value['goods_name']."'库存不足");
                }
                //减库存
                db('store_goods')->where('id',$storeGoodsId)->dec('stock',$value['num'])->dec('real_stock',$value['num'])->update();


                $startSale = $goods['start_sale'] ? $goods['start_sale'] : $goodsP['start_sale'];
                if ($type == 1 && $value['num'] < $startSale) {
                    $this->error("'".$value['goods_name']."'起售数量最低为".$startSale);
                }
                //计算价格的时候按用户角色比例计算
                $discount1 = 100;
                switch ($user['type']) {
                    case 2:
                        $discount1 = $value['highuser_discount'];
                        break;
                    case 3:
                        //这里合伙人零售  和 合伙人采购用的是同一个比例
                        $discount1 = $value['partner_discount'];
                        break;
                }
                $totalAmount+=round($value['price']*($discount1/100)*$value['num'],2);
            }
            $manJian = [
                'full_price'=>0,
                'minus_price'=>0
            ];
            if (!empty($activeId)) {
                $manJian = getOrderManJian($activeId,$storeId);
                if ($manJian['code'] == 201) {
                    Db::rollback();
                    $this->error($manJian['msg']);
                }
                $manJian = $manJian['data'];
            }

            //var_dump($manJian);die;
            //默认分销比例0
            $ratioOne = 0;
            $ratioTwo = 0;
            /***分销金额计算***/
            if (!empty($user['pid'])) {
                $pUser = db('user')->where('id',$user['pid'])->find();
                $pUser2 = db('user')->where('id',$user['two_pid'])->find();
                
                foreach ($cart AS $key => $value) {
                    //一级
                    if ($pUser['type'] == 2) {
                        //默认高级用户
                        $ratioOne = $value['highuser_one'];
                    } elseif ($pUser['type'] == 3) {
                        //合伙人
                        $ratioOne = $value['partner_one'];
                    }
                    //二级
                    if (!empty($pUser2)) {
                        if ($pUser2['type'] == 2) {
                            //默认高级用户
                            $ratioTwo = $value['highuser_two'];
                        } elseif ($pUser2['type'] == 3) {
                            //合伙人
                            $ratioTwo = $value['partner_two'];
                        }
                    }
                    
                    $discount = 100;
                    switch ($user['type']) {
                        case 2:
                            $discount = $value['highuser_discount'];
                            break;
                        case 3:
                            //这里合伙人零售  和 合伙人采购用的是同一个比例
                            $discount = $value['partner_discount'];
                            break;
                    }
                    $orderPriceS = round($value['price']*($discount/100),2);//商品实付金额



                    $fx_price+=round($orderPriceS*($ratioOne/100),2)*$value['num'];
                    $fx_price_two+=round($orderPriceS*($ratioTwo/100),2)*$value['num'];

                    $fxGoodsIdPriceArr[$value['goods_id']] = round($orderPriceS*($ratioOne/100),2);//单个商品的分销金额

                    $fxGoodsIdPriceArrTwo[$value['goods_id']] = round($orderPriceS*($ratioTwo/100),2);//单个商品的分销金额
                }
            }
            $orderType = 0;
            if ($user['type'] == 1) {
                $orderType = 1;
            } elseif ($user['type'] == 2) {
                $orderType = 1;
            } elseif ($user['type'] == 3) {
                $orderType = 2;
            }
            /***创建订单***/
            $orderInsert = [
                'order_no'=>generateOrderNumber(),
                'order_type'=>$orderType,
                'user_id'=>$userId,
                'store_id'=>$storeId,
                'price'=>$totalAmount-$manJian['minus_price'],
                'order_status'=>0,
                'door_type'=>$type == 1 ? 2 : 1,
                'memo'=>$remark,
                'act_id'=>$activeId,
                'full_price'=>$manJian['full_price'],
                'minus_price'=>$manJian['minus_price'],
                'p_user_id'=>$user['pid'],
                'fx_price'=>$fx_price,
                'fx_pricetwo'=>$fx_price_two,
                'p_user_idtwo'=>$user['two_pid'],
                'address_id'=>$addressId,
                'addtime'=>time(),
                'role_type'=>getOrderRole($orderType,$user['type'])
            ];
            if ($type == 1) {
                //邮寄
                $orderInsert['name'] = $address['name'];
                $orderInsert['tel'] = $address['tel'];
                $orderInsert['province'] = $address['province'];
                $orderInsert['city'] = $address['city'];
                $orderInsert['area'] = $address['area'];
                $orderInsert['address'] = $address['address'];
            } else {
                //自提
                $orderInsert['name'] = $name;
                $orderInsert['tel'] = $tel;
                $orderInsert['province'] = $store['province'];
                $orderInsert['city'] = $store['city'];
                $orderInsert['area'] = $store['area'];
                $orderInsert['address'] = $store['address'];
            }

            //创建订单
            $orderId = db('order')->insertGetId($orderInsert);
            /******创建订单商品&&更新采购单商品******/
            //创建订单商品

            foreach ($cart AS $kk => $vv) {

                $discount = 100;
                switch ($user['type']) {
                    case 2:
                        $discount = $vv['highuser_discount'];
                        break;
                    case 3:
                        //这里合伙人零售  和 合伙人采购用的是同一个比例
                        $discount = $vv['partner_discount'];
                        break;
                }
                $goodsPay = round($vv['price']*($discount/100),2);//商品实付金额

                //创建订单商品
                $orderGoodsId = db('order_goods')->insertGetId([
                    'goods_id'=>$vv['goods_id'],
                    'order_id'=>$orderId,
                    'goods_name'=>$vv['goods_name'],
                    'cost_price'=>$vv['cost_price'],
                    'price'=>$vv['price'],
                    'discount'=>$discount,
                    'order_price'=>$goodsPay,
                    'num'=>$vv['num'],
                    'spec_name'=>$vv['spec_name'],
                    'goods_pic'=>$vv['image'],
                    'addtime'=>time()
                ]);

                $caiGoodsList = db('order_goods_store')
                ->where('store_id',$storeId)
                ->where('goods_id',$vv['goods_id'])
                ->where('authen','in',[0,3])
                ->where('order_id',0)
                ->where('cai_successtime','>',0)
                ->order('addtime ASC')
                ->select();

                if (count($caiGoodsList) < $vv['num']) {
                    Db::rollback();
                    $this->error('库存不足-1001');exit();
                }

                //采购单数量是拆开的，需要循环
                for ($i=0; $i<$vv['num']; $i++)
                {
                    //采购单未售出的这个商品
                    $caiGoods = $caiGoodsList[$i];
                    $orderGoodsStore = db('order_goods_store')->where('id',$caiGoods['id'])->lock(true)->find();
                    if ($orderGoodsStore['order_id'] > 0) {
                        Db::rollback();
                        $this->error('当前下单人数较多，请再试一次-1005');exit();
                    }
                    //更新采购单商品
                    db('order_goods_store')->where('id',$caiGoods['id'])->update([
                        'order_id'=>$orderId,
                        'order_goods_id'=>$orderGoodsId,
                        'p_user_id'=>$user['pid'],
                        'p_user_idtwo'=>$user['two_pid'],
                        'fx_price'=>$fxGoodsIdPriceArr ? $fxGoodsIdPriceArr[$vv['goods_id']] : 0,
                        'fx_pricetwo'=>$fxGoodsIdPriceArrTwo ? $fxGoodsIdPriceArrTwo[$vv['goods_id']] : 0,
                        'fx_rate'=>$ratioOne,
                        'fx_ratetwo'=>$ratioTwo,
                        'order_price'=>$goodsPay,
                        'lirun'=>bcsub($goodsPay,$caiGoods['goods_price'],2),
                        //'promotion_price_pt'=>$tuiGuang
                    ]);
                }

            }

            /***清除购物车***/
            db('cart')->where('id','in',$cartId)->update([
                'is_delete'=>1
            ]);

            /***生成支付参数****/
//            $aesUtil = new Aesutils();
//            $order_info = [];
//            $order_info['order_num'] = $order_no;
//            $order_info['openid'] = $open_id;//用户openid
//            $order_info['notify_url'] = $notify;//回调地址
//            //$order_info['total_amount'] = $price;//金额
//            $order_info['total_amount'] = 1;//金额
//            $order_info['description'] =  $description;//描述
//            // $order_info['sub_mchid'] = $store_info['sub_mchid'];
//            $order_info['sub_mchid'] = $sub_mchid;
//
//            $order_info['profit_sharing']=false;//是否分账
//
//            $backList = $aesUtil->store_pay_new($order_info);
             $backList = [
                 'order_id'=>$orderId
             ];

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('请求成功',$backList);
    }


    /**
     * 立即购买创建订单
     * @path api/order/order/createOrderQuick
     */
    public function createOrderQuick()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
            $type = $this->request->post('type');//1快递邮寄  2到店自提
            $addressId = $this->request->post('address_id',0);
            $storeId = $this->request->post('store_id',$storeId);//空间/中心/自提点ID
            $goodsId = $this->request->post('goods_id');
            $num = $this->request->post('num');
            $remark = $this->request->post('remark');
            $name = $this->request->post('name');
            $tel = $this->request->post('tel');
            $activeId = $this->request->post('active_id');
            $totalAmount = 0;
            $fx_price = 0;//一级分销总金额
            $fx_price_two = 0;//二级分销总金额
            $fxGoodsIdPriceArr = [];//单个商品一级分销金额  例：goodsId=>1.1
            $fxGoodsIdPriceArrTwo = [];//单个商品二级分销金额  例：goodsId=>1.1
            /***过滤参数***/
            //var_dump($type,$cartId);die;
            if (empty($type) || empty($goodsId)) {
                Db::rollback();
                $this->error('缺少参数');
            }

            $isManJian = true;//默认开启满减
            $highuserManjian = db('config')->where(['name'=>'highuser_manjian','group'=>'basic'])->value('value');
            $partnerManjian = db('config')->where(['name'=>'partner_manjian','group'=>'basic'])->value('value');
            $user = db('user')->where('id',$userId)->find();
            if ($user['type'] == 2 && $highuserManjian == 0) {
                //高级用户
                $isManJian = false;
            }
            if ($user['type'] == 3 && $partnerManjian == 0) {
                //合伙人
                $isManJian = false;
            }
            if ($isManJian == false && !empty($activeId)) {
                Db::rollback();
                $this->error('高级用户和合伙人，暂时不支持使用满减活动下单');
            }

            $store = db('store')->where('id',$storeId)->find();
            $address = db('address')->where('id',$addressId)->find();
            $goods = db('goods')->where('id',$goodsId)->find();
            $storeGoods = db('store_goods')->where(['store_id'=>$storeId,'goods_id'=>$goodsId])->find();
            $startSale = $storeGoods['start_sale'] ? $storeGoods['start_sale'] : $goods['start_sale'];

            if ($goods['is_on_sale'] < 1) {
                Db::rollback();
                $this->error("产品已下架");
            }

            if (empty($goods)) {
                Db::rollback();
                $this->error('商品不存在');
            }
            if ($type == 1 && $num < $startSale) {
                $this->error("'".$goods['goods_name']."'起售数量最低为".$startSale);
            }

            $storeGoodsId = $storeGoods['id'];
            $goodsStock = db('store_goods')->where('id',$storeGoodsId)->lock(true)->find();
            if ($goodsStock['stock'] < $num) {
                Db::rollback();
                $this->error("'".$goods['goods_name']."'库存不足");
            }

            //减库存
            db('store_goods')->where('id',$storeGoodsId)->dec('stock',$num)->dec('real_stock',$num)->update();
            //计算价格的时候按用户角色比例计算
            $discount1 = 100;
            switch ($user['type']) {
                case 2:
                    $discount1 = $goods['highuser_discount'];
                    break;
                case 3:
                    //这里合伙人零售  和 合伙人采购用的是同一个比例
                    $discount1 = $goods['partner_discount'];
                    break;
            }
            $totalAmount = round($goods['price']*($discount1/100)*$num,2);

            $manJian = [
                'full_price'=>0,
                'minus_price'=>0
            ];
            if (!empty($activeId)) {
                $manJian = getOrderManJian($activeId,$storeId);
                if ($manJian['code'] == 201) {
                    Db::rollback();
                    $this->error($manJian['msg']);
                }
                $manJian = $manJian['data'];
            }

            //默认分销比例0
            $ratioOne = 0;
            $ratioTwo = 0;
            /***分销金额计算***/
            if (!empty($user['pid'])) {
                $pUser = db('user')->where('id',$user['pid'])->find();
                $pUser2 = db('user')->where('id',$user['two_pid'])->find();

                //一级
                if ($pUser['type'] == 2) {
                    //默认高级用户
                    $ratioOne = $goods['highuser_one'];
                
                } elseif ($pUser['type'] == 3) {
                    //合伙人
                    $ratioOne = $goods['partner_one'];
                
                }

                //二级
                if (!empty($pUser2)) {
                    if ($pUser2['type'] == 2) {
                        //默认高级用户
                        $ratioTwo = $goods['highuser_two'];
                    } elseif ($pUser2['type'] == 3) {
                        //合伙人
                        $ratioTwo = $goods['partner_two'];
                    }
                }

                $discount = 100;
                switch ($user['type']) {
                    case 2:
                        $discount = $goods['highuser_discount'];
                        break;
                    case 3:
                        //这里合伙人零售  和 合伙人采购用的是同一个比例
                        $discount = $goods['partner_discount'];
                        break;
                }
                $orderPriceS = round($goods['price']*($discount/100),2);//商品实付金额


                $fx_price = round($orderPriceS*($ratioOne/100),2)*$num;
                $fx_price_two+=round($orderPriceS*($ratioTwo/100),2)*$num;

                $fxGoodsIdPriceArr[$goods['id']] = round($orderPriceS*($ratioOne/100),2);//单个商品的分销金额

                $fxGoodsIdPriceArrTwo[$goods['id']] = round($orderPriceS*($ratioTwo/100),2);//单个商品的分销金额

            }
            $orderType = 0;
            if ($user['type'] == 1) {
                $orderType = 1;
            } elseif ($user['type'] == 2) {
                $orderType = 1;
            } elseif ($user['type'] == 3) {
                $orderType = 2;
            }
            /***创建订单***/
            $orderInsert = [
                'order_no'=>generateOrderNumber(),
                'order_type'=>$orderType,
                'user_id'=>$userId,
                'store_id'=>$storeId,
                'price'=>$totalAmount-$manJian['minus_price'],
                'order_status'=>0,
                'door_type'=>$type == 1 ? 2 : 1,
                'memo'=>$remark,
                'act_id'=>$activeId,
                'full_price'=>$manJian['full_price'],
                'minus_price'=>$manJian['minus_price'],
                'p_user_id'=>$user['pid'],
                'fx_price'=>$fx_price,
                'fx_pricetwo'=>$fx_price_two,
                'p_user_idtwo'=>$user['two_pid'],
                'address_id'=>$addressId,
                'role_type'=>getOrderRole($orderType,$user['type']),
                'addtime'=>time(),
            ];
            if ($type == 1) {
                //邮寄
                $orderInsert['name'] = $address['name'];
                $orderInsert['tel'] = $address['tel'];
                $orderInsert['province'] = $address['province'];
                $orderInsert['city'] = $address['city'];
                $orderInsert['area'] = $address['area'];
                $orderInsert['address'] = $address['address'];
            } else {
                //自提
                $orderInsert['name'] = $name;
                $orderInsert['tel'] = $tel;
                $orderInsert['province'] = $store['province'];
                $orderInsert['city'] = $store['city'];
                $orderInsert['area'] = $store['area'];
                $orderInsert['address'] = $store['address'];
            }

            //创建订单
            $orderId = db('order')->insertGetId($orderInsert);
            /******创建订单商品&&更新采购单商品******/
            //创建订单商品



                $discount = 100;
                switch ($user['type']) {
                    case 2:
                        $discount = $goods['highuser_discount'];
                        break;
                    case 3:
                        //这里合伙人零售  和 合伙人采购用的是同一个比例
                        $discount = $goods['partner_discount'];
                        break;
                }
                $goodsPay = round($goods['price']*($discount/100),2);//商品实付金额

                //创建订单商品
                $orderGoodsId = db('order_goods')->insertGetId([
                    'goods_id'=>$goods['id'],
                    'order_id'=>$orderId,
                    'goods_name'=>$goods['goods_name'],
                    'cost_price'=>$goods['cost_price'],
                    'price'=>$goods['price'],
                    'discount'=>$discount,
                    'order_price'=>$goodsPay,
                    'num'=>$num,
                    'spec_name'=>$goods['spec_name'],
                    'goods_pic'=>$goods['image'],
                    'addtime'=>time()
                ]);

                $caiGoodsList = db('order_goods_store')
                    ->where('store_id',$storeId)
                    ->where('goods_id',$goods['id'])
                    ->where('authen','in',[0,3])
                    ->where('order_id',0)
                    ->where('cai_successtime','>',0)
                    ->order('addtime ASC')
                    ->select();
                if (count($caiGoodsList) < $num) {
                    Db::rollback();
                    $this->error('库存不足-1002');exit();
                }

                //采购单数量是拆开的，需要循环
                for ($i=0; $i<$num; $i++)
                {
                    //采购单未售出的这个商品
                    $caiGoods = $caiGoodsList[$i];
                    $orderGoodsStore = db('order_goods_store')->where('id',$caiGoods['id'])->lock(true)->find();
                    if ($orderGoodsStore['order_id'] > 0) {
                        Db::rollback();
                        $this->error('当前下单人数较多，请再试一次-1005');exit();
                    }
                    //更新采购单商品
                    db('order_goods_store')->where('id',$caiGoods['id'])->update([
                        'order_id'=>$orderId,
                        'order_goods_id'=>$orderGoodsId,
                        'p_user_id'=>$user['pid'],
                        'p_user_idtwo'=>$user['two_pid'],
                        'fx_price'=>$fxGoodsIdPriceArr ? $fxGoodsIdPriceArr[$goods['id']] : 0,
                        'fx_pricetwo'=>$fxGoodsIdPriceArrTwo ? $fxGoodsIdPriceArrTwo[$goods['id']] : 0,
                        'fx_rate'=>$ratioOne,
                        'fx_ratetwo'=>$ratioTwo,
                        'order_price'=>$goodsPay,
                        'lirun'=>bcsub($goodsPay,$caiGoods['goods_price'],2),
                    ]);
                }
                

            /***生成支付参数****/
            $backList = [
                'order_id'=>$orderId
            ];

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('请求成功',$backList);
    }

    /**
     * 查看订单
     * @path api/order/order/lookOrder
     */
    public function lookOrder()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;
        $orderId = $this->request->get('order_id',0);
        $residueTime = 0;//剩余支付时间
        $order = db('order')->where(['id'=>$orderId,'user_id'=>$userId])->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }

        $province = db('area')->where('id',$order['province'])->value('name');
        $city = db('area')->where('id',$order['city'])->value('name');
        $area = db('area')->where('id',$order['area'])->value('name');
        $order['province_name'] = $province;
        $order['city_name'] = $city;
        $order['area_name'] = $area;
        $order['addtime'] = date('Y-m-d H:i:s',$order['addtime']);

        $order['pay_time'] = date('Y-m-d H:i:s',$order['pay_time']);
        $order['delivery_time'] = date('Y-m-d H:i:s',$order['delivery_time']);
        $order['order_qr_time'] = date('Y-m-d H:i:s',$order['order_qr_time']);
        $order['qx_time'] = date('Y-m-d H:i:s',$order['qx_time']);

        //到店自提
        $store = db('store')->where('id',$storeId)->find();
        $province1 = db('area')->where('id',$store['province'])->value('name');
        $city1 = db('area')->where('id',$store['city'])->value('name');
        $area1 = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province1;
        $store['city_name'] = $city1;
        $store['area_name'] = $area1;
        $address1 = [
            'store_name'=>$store['store_name'],
            'store_phone'=>$store['tel'],
            'province_name'=>$province1,
            'city'=>$city1,
            'area'=>$area1,
            'address'=>$store['address'],
            'business_start_time'=>$store['business_start_time'],
            'business_end_time'=>$store['business_end_time'],
            'name' => '',
            'tel' => ''
        ];

        $address1['name'] = $order['name'];
        $address1['tel'] = $order['tel'];




        $orderGoods = db('order_goods')->where('order_id',$order['id'])->select();
        $orderGoods = addWebSiteUrl($orderGoods,['goods_pic']);
        $goodsTotal = 0;
        foreach ($orderGoods AS $key => $value) {
            $goodsTotal=bcadd($goodsTotal,bcmul($value['order_price'],$value['num'],2),2);
        }
        if ($order['order_status'] == 0) {
            $residueTime = time()-strtotime($order['addtime']);
            $residueTime = 1800-$residueTime;
            if ($residueTime <= 0) {
                $residueTime = 0;
            }
            $residueTime = gmdate("i:s", $residueTime);
        }

        //查看快递
        $order['delivery_name'] = db('express_code')->where('id',$order['delivery_code'])->value('title');
        $order['goods_total'] = $goodsTotal;
        $order['residue_time'] = $residueTime;
        $order['order_goods'] = $orderGoods;
        $order['store_info'] = $address1;
        $this->success('请求成功',$order);
    }

    /**
     * 取消订单
     * @path api/order/order/cancleOrder
     */
    public function cancleOrder()
    {
        Db::startTrans();
        try{
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $orderId = $this->request->post('order_id',0);
            $orderInfo = db('order')->where(['id'=>$orderId,'user_id'=>$userId])->find();
            if (empty($orderInfo)) {
                Db::rollback();
                $this->error('订单不存在');
            }

            db('order')->where('id',$orderId)->update([
                'order_status'=>5,
                'qx_time'=>time(),
                'cancle_type'=>2
            ]);

            //加库存
            $orderGoods = db('order_goods')->where('order_id',$orderId)->select();
            foreach ($orderGoods AS $key => $value) {
                
                $storeGoodsId = db('store_goods')->where(['store_id'=>$orderInfo['store_id'],'goods_id'=>$value['goods_id']])->value('id');
                db('store_goods')->where('id',$storeGoodsId)->lock(true)->find();

                db('store_goods')->where('id',$storeGoodsId)->inc('stock',$value['num'])->inc('real_stock',$value['num'])->update();
            }

            //还原采购单
            db('order_goods_store')->where('order_id',$orderId)->update([
                'order_id'=>0,
                'order_goods_id'=>0,
                'p_user_id'=>0,
                'p_user_idtwo'=>0,
                'fx_price'=>0,
                'fx_pricetwo'=>0,
                'order_price'=>0,
                'lirun'=>0,
            ]);

            //订单是否可退
            if ($orderInfo['is_ketui'] == 0) {
                db('order')->where('id',$orderId)->update([
                    'is_ketui'=>1
                ]);
            }


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('取消成功');
    }

    /**
     * 确认收货
     * @path api/order/order/confirmOrder
     */
    public function confirmOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
            $orderId = $this->request->post('order_id', 0);
            $store = db('store')->where('id', $storeId)->find();
            $user = db('user')->where('id',$userId)->find();
            $orderInfo = db('order')->where(['user_id' => $userId, 'id' => $orderId])->find();
            if (empty($orderInfo)) {
                Db::rollback();
                $this->error('订单不存在');
            }
            if (in_array($orderInfo['order_status'], [0, 4, 5])) {
                Db::rollback();
                $this->error('订单状态错误');
            }


            /**********更新订单状态**********/
            db('order')->where(['user_id' => $userId, 'id' => $orderId])->update([
                'order_status' => 4,
                'order_qr_time' => time(),
                'ti_code'=>0
            ]);

            /***升级高级用户操作***/
            if ($user['type'] == 1) {
                $buyNum = db('config')->where(['name'=>'highuser_count','group'=>'basic'])->value('value');
                $buyPrice = db('config')->where(['name'=>'highuser_price','group'=>'basic'])->value('value');
                $userAllPrice = db('order')->where(['user_id'=>$userId])->where('order_status','4')->sum('price');
                $orderGoodsNum = db('order')->alias('a')->join('order_goods b','a.id=b.order_id','left')->where(['a.user_id'=>$userId])->where('a.order_status','4')->sum('num');
                if ($orderGoodsNum >= $buyNum || $userAllPrice >= $buyPrice) {
                    db('user')->where('id',$userId)->update([
                        'type'=>2
                    ]);
                }
            }


            /********下单送积分*********/
            $userScoreRatio = db('integral_score_rule')->where('type',4)->value('ratio');
            $userScoreRatio = $userScoreRatio ? $userScoreRatio : 0;
            $sendScore = round($orderInfo['price']*($userScoreRatio/100));

            if ($sendScore > 0) {
                $uLockInfo = db('user')->where('id',$userId)->lock(true)->find();
                db('user')->where('id',$userId)->setInc('integral',$sendScore);
                $gDay = db('integral_score_rule')->where('type',5)->value('day');
                $guoQi = strtotime(date('Y-m-d'))+86400+$gDay*86400;
                db('integral_change_log')->insert([
                    'user_id'=>$userId,
                    'store_id'=>$storeId,
                    'scene'=>4,
                    'score'=>$sendScore,
                    'total_score'=>$uLockInfo['integral']+$sendScore,
                    'residue_score'=>$sendScore,
                    'type'=>2,
                    'order_id'=>$orderId,
                    'exptime'=>date('Y-m-d H:i:s',$guoQi),
                    'addtime'=>date('Y-m-d H:i:s'),
                ]);
            }
            

            /*******发放各种佣金*********/
            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            $fxPrice = 0;//一级分销佣金
            $fxPriceTwo = 0;//二级分销佣金
            $pUserId = 0;//分销人用户id
            $pUserIdTwo = 0;//二级分销用户id
            $rate = 0;
            $rateTwo = 0;

            foreach ($orderGoods AS $key => $value) {
                $goodsStore = db('order_goods_store')->where(['order_id' => $orderId, 'order_goods_id' => $value['id']])->select();
                foreach ($goodsStore AS $k => $v) {
                    $fxPrice += $v['fx_price'];
                    $fxPriceTwo += $v['fx_pricetwo'];
                    $pUserId = $v['p_user_id'];
                    $pUserIdTwo = $v['p_user_idtwo'];
                    $rate = $v['fx_rate'];
                    $rateTwo = $v['fx_ratetwo'];
                }
                //更新商品销量
                db('goods')->where('id',$value['goods_id'])->setInc('salecount',$value['num']);
            }

            //1=采购发放,2=核销发送
            $promotionRule = db('promotion_rule')->limit(0, 1)->value('promotion_status');
            if ($promotionRule == 2) {
                //业务员佣金
                $commissionServices = new Commission();
                $yeWu = $commissionServices->yeWuPrice($orderId,$storeId);
                if ($yeWu == false) {
                    Db::rollback();
                    $this->error('业务员佣金发放失败');
                }
                //推广佣金
                $tuiGuang = $commissionServices->promotionPrice($orderId,$storeId);
                if ($tuiGuang == false) {
                    Db::rollback();
                    $this->error('推广佣金发放失败');
                }
                //更新order_goods_store发放状态
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'isfa' => 1,
                    'fa_time'=>time(),
                    'successtime'=>time()
                ]);
            } else {
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'successtime'=>time()
                ]);
            }
            //分销佣金
            if (!empty($pUserId) && in_array($user['type'],[1,2])) {
                $user11 = db('user')->where('id',$pUserId)->find();
                $type = $user11['type'];
                if ($type == 2) {
                    $type = 1;
                }
                if ($type == 3) {
                    $type = 2;
                }

                //合伙人未首次缴费，未储值
                if ($user11['is_card_pay'] == 0 && $user11['type'] == 3) {

                } else {
                    if($fxPrice>0 && $user11['type']!=0)
                    {
                        db('fenxiao_log')->insert([
                            'user_id'=>$pUserId,
                            'to_user_id'=>$userId,
                            'order_price'=>$orderInfo['price'],
                            'order_id'=>$orderId,
                            'price'=>$fxPrice,
                            'store_id'=>$orderInfo['store_id'],
                            'rate'=>$rate,
                            'type'=>$type,
                            'addtime'=>time()
                        ]);
    
                        //更新账户余额
                        db('user')->where('id',$pUserId)->lock(true)->find();
                        db('user')->where('id',$pUserId)->setInc('commission_money',$fxPrice);
                    }
                    
                }

                if (!empty($pUserIdTwo)) {
                    $user22 = db('user')->where('id',$pUserIdTwo)->find();
                    $type1 = $user22['type'];
                    if ($type1 == 2) {
                        $type1 = 1;
                    }
                    if ($type1 == 3) {
                        $type1 = 2;
                    }
                    //合伙人未首次缴费，未储值
                    if ($user22['is_card_pay'] == 0 && $user22['type'] == 3) {

                    } else {
                        if($fxPriceTwo>0 && $user22['type']!=0)
                        {
                            db('fenxiao_log')->insert([
                                'user_id'=>$pUserIdTwo,
                                'to_user_id'=>$userId,
                                'order_price'=>$orderInfo['price'],
                                'order_id'=>$orderId,
                                'price'=>$fxPriceTwo,
                                'store_id'=>$orderInfo['store_id'],
                                'rate'=>$rateTwo,
                                'type'=>$type1,
                                'addtime'=>time()
                            ]);
                            //更新账户余额
                            db('user')->where('id',$pUserIdTwo)->lock(true)->find();
                            db('user')->where('id',$pUserIdTwo)->setInc('commission_money',$fxPriceTwo);
                        }
                        
                    }
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('已确认收货');
    }


    /**
     * 修改订单收货地址
     * @path api/order/order/editOrderAddress
     */
    public function editOrderAddress()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $orderId = $this->request->post('order_id',0);
        $addressId = $this->request->post('addressId',0);
        $orderInfo = db('order')->where(['id'=>$orderId,'user_id'=>$userId])->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }
        $address = db('address')->where('id',$addressId)->find();
        db('order')->where('id',$orderId)->update([
            'address_id'=>$addressId,
            'name'=>$address['name'],
            'tel'=>$address['tel'],
            'province'=>$address['province'],
            'city'=>$address['city'],
            'area'=>$address['area'],
        ]);
        $this->success('修改成功');
    }

    /**
     * 订单核销码
     * @path api/order/order/orderCode
     */
    public function orderCode()
    {
        $orderId = $this->request->param('order_id',0);
        $orderInfo = db('order')->field('id,ti_code')->where('id',$orderId)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }
        $this->success('请求成功',$orderInfo);
    }

        //立即支付
    public function quickPay()
    {
        $storeId = $this->auth->store_id;
        $orderId = $this->request->post('order_id');
        $activeId = $this->request->post('active_id');
        $addressId = $this->request->post('address_id');
        $remark = $this->request->post('remark');
        $order = db('order')->where('id',$orderId)->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }
        // 启动事务
        Db::startTrans();
        try{
            $tiCode = generateUniqueCode($length=4,$storeId,2);
            $orderUpdateArr = [
                'pay_time'=>time(),
                'ti_code' => $tiCode,
                'order_status' => $order['door_type'] == 1 ? 2 : 1,
            ];
            if (!empty($addressId)) {
                $address = db('address')->where('id',$addressId)->find();
                if (!empty($address)) {
                    $orderUpdateArr['name'] = $address['name'];
                    $orderUpdateArr['tel'] = $address['tel'];
                    $orderUpdateArr['province'] = $address['province'];
                    $orderUpdateArr['city'] = $address['city'];
                    $orderUpdateArr['area'] = $address['area'];
                    $orderUpdateArr['address'] = $address['address'];
                }
            }
            if (!empty($remark)) {
                $orderUpdateArr['memo'] = $remark;
            }

            //满减信息
            if (empty($activeId)) {
                if (!empty($order['act_id'])) {
                    db('order')->where('id',$orderId)->setInc('price',$order['minus_price']);
                    $orderUpdateArr['act_id'] = 0;
                    $orderUpdateArr['full_price'] = 0;
                    $orderUpdateArr['minus_price'] = 0;
                }
            } else {
                $manJian = getOrderManJian($activeId,$storeId);
                if ($manJian['code'] == 201) {
                    Db::rollback();
                    $this->error($manJian['msg']);
                }
            }
            /*更新佣金发放模式*/
            $orderUpdateArr['promotion_status'] = 1;

            db('order')->where('id',$orderId)->update($orderUpdateArr);
            
            /**中心/空间货款实时入储值**/
            $storeId = $order['store_id'];
            $orderGoods = db('order_goods_store')->where(['store_id'=>$storeId,'order_id'=>$orderId])->select();
            
            $orderCostPrice = 0;//订单成本价
            foreach ($orderGoods AS $key => $value) {
                $orderCostPrice = bcadd($orderCostPrice,$value['cai_order_price'],2);
            }
            $store = db('store')->where('id',$storeId)->lock(true)->find();
            db('store')->where('id',$storeId)->inc('storage_balance',$orderCostPrice)->update();

            /**增加储值资金变动明细**/
            db('card_log')->insert([
                'type'=>$store['type'],
                'store_id'=>$storeId,
                'price'=>$orderCostPrice,
                'new_price'=>bcadd($orderCostPrice,$store['storage_balance'],2),
                'pay_type'=>8,//货款到账
                'ordernum'=>$order['order_no'],
                'is_first'=>2,
                'ispay'=>1,
                'addtime'=>time(),
                'user_del'=>0
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $backList = [];
        $this->success('支付成功',$backList);
    }
}
